/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projekt;

import SaveData.Builder;
import SaveData.CharFile;
import SaveData.HTMLTextConverter;
import SaveData.SaveData;
import java.util.*;
import strategy.OneToOne;
import strategy.Strategy;
import strategy.ThreeToThree;

/**
 *
 * @author ADAM
 */
public class Mediator extends javax.swing.JFrame {

    private static Mediator instance;
    private static final int sizeOfCompareList = 5;
    private static Map<Integer,String> mMessages = new HashMap<>();
    private static Map<Integer,Double> mResults = new HashMap<>();
    private static List<Strategy> mAlgo = new ArrayList<>();
    private static Map<Integer,Pair<List<String>,List<List<String>>>> mLists = new HashMap<>();
    private Mediator() 
    {
        initComponents();
        this.setVisible(true);
        
    }

   
    
    
    public static Mediator getRef() 
    {
        if(instance == null) 
        {
            synchronized(Mediator.class) 
            {
                if(instance == null) 
                {                            
                    instance = new Mediator();
                    System.out.println("Tworzę nową instancje"); 
                    mAlgo.add(new OneToOne(null, null));
                    mAlgo.add(new ThreeToThree(null, null));
                    instance.configure();
                }
            }
        }else
        {
            //System.out.println("Instancja już istnieje");
        }
        
        return instance;
    }
    
    private void divide(long ile)
    {
        Set<Integer> tempSet = mResults.keySet();
        for(Integer elem:tempSet)
        {
            mResults.put(elem,mResults.get(elem)/ile);
        }
        for(Strategy elem:mAlgo)
        {
            String str = ". "+mResults.get(elem.getIndex())+"\n";
            mMessages.put(elem.getIndex(),elem.getNazwaAlgo()+str);
            showTable();
        }
    }
    public void runAlgo(List<String> pmList)
    {
        List<List<String>> tempList = randList(sizeOfCompareList, pmList);
        for(Strategy elem:mAlgo)
        {
            for(int i=0;i<pmList.size();i++)
            {
                elem.set(pmList.get(i).substring(0, pmList.get(i).length()-1),(ArrayList)tempList.get(i));
                elem.run();
            }
        }
    }
    private List<List<String>> randList(int k,List<String> pmList)
    {
        List<List<String>> listofList = new ArrayList<>();
        String [] tab = {"A","R","N","D","C","Q","E","G","H","I","L","K","M","F","P","S","T","W","Y","V"};
        for(String elem:pmList)
        {
            List<String> list = new ArrayList<>();
            
            for(int i=0;i<k;i++)
            { 
                int length = elem.length();
                StringBuilder sb = new StringBuilder();
                for(int j = 0;j<length;j++)
                {                
                    int a = (int)(Math.random()*(19.9999999));
                    sb.append(tab[a]);
                }
                list.add(sb.toString());
            }
            listofList.add(list);
            
        }
        return listofList;
    }
     
     
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane2.setViewportView(jTextArea1);

        jButton2.setText("Zakończ");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Cofnij zapis");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton1.setText("Zapisz do pliku");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 36, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(47, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void clear()
    {
        mMessages = new HashMap<>();
        showTable();
    }
    public void remove(int i)
    {
        mMessages.remove(i);
        showTable();
    }
    public void update(int pmIndex)
    {
        String str = ". Trwa wczytywanie danych...\n";
        mMessages.put(pmIndex,(pmIndex-1000)+str);
        showTable();
    }
    public void update(String pmNazwaAlgorytmu,int pmIndex)
    {
        String str = ". Trwa obliczanie podobieństwa...\n";
        mMessages.put(pmIndex,pmNazwaAlgorytmu+str);
        showTable();
    }
    public void update(String pmNazwaAlgorytmu,int pmIndex,String pmResult)
    {
        if(mResults.containsKey(pmIndex))
        {
            mResults.put(pmIndex,(mResults.get(pmIndex)+Double.parseDouble(pmResult)));
        }else
        {
            mResults.put(pmIndex,Double.parseDouble(pmResult));
        }
        
        String str = ". Trwa obliczanie podobieństwa... "+mResults.get(pmIndex)+"\n";
        mMessages.put(pmIndex,pmNazwaAlgorytmu+str);
        showTable();
    }
    private void showTable()
    {
        String temp = "";
        SortedSet<Integer> tempSet = new TreeSet<Integer>(mMessages.keySet());
        for(Integer elem:tempSet)
        {
            temp+=mMessages.get(elem);
        }
        jTextArea1.setText(temp);
    }
    private void showEndTable()
    {
        String temp = "";
        SortedSet<Integer> tempSet = new TreeSet<Integer>(mMessages.keySet());
        for(Integer elem:tempSet)
        {
            temp+=mMessages.get(elem);
        }
        jTextArea1.setText(temp+"\nObliczanie skończone ;)");
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
//        if (save != null) {
//            save.backChanges();
//            String temp = save.showDataToSave();
//            save = new CharFile("output", "html");
//            save.clear();
//            save.write(temp);
//            save.close();
//        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//        save = new CharFile("output", "html");
//        save.write(lvConverter.getText());
//        save.close();


    }//GEN-LAST:event_jButton1ActionPerformed
    
    private long count(List<List<String>> pmList)
    {
        long ile = 0;
        for(List<String> elem:pmList)
        {
            ile+=elem.size();
            
        }
        return ile;
    }
    private void configure()
    {
        String mUrl = "jdbc:mysql://localhost:3306/ad";
        String mUserName = "root";
        String mPassword = "qazwsx12";
        Data data = new DNAData(new MySqlDBConnector(mUrl,mUserName, mPassword),1);
        MyIterator iter = new MyIterator(data);
        iter.Next();
        divide(count(data.getAllData()));
        showEndTable();
<<<<<<< .mine
<<<<<<< .mine
        ArrayList<String> tempResult = new ArrayList<>();
        tempResult.add("");
        Builder HTML = new HTMLTextConverter(tempResult);
        for (Strategy tempStrategy : mAlgo) {
            HTML.parseString(tempStrategy.getNazwaAlgo());
            HTML.makeNewRow();
            HTML.parseString(String.valueOf(mResults.get(tempStrategy.getIndex())));
            HTML.makeNewLine();
        }
        SaveData tempSave = new CharFile("result", "htm");
        tempSave.write(HTML.endText());
=======
>>>>>>> .r10
=======
        ArrayList<String> tempResult = new ArrayList<String>();
        tempResult.add("");
        Builder HTML = new HTMLTextConverter(tempResult);
        for (Strategy tempStrategy : mAlgo) {
            HTML.parseString(tempStrategy.getNazwaAlgo());
            HTML.makeNewRow();
            HTML.parseString(String.valueOf(mResults.get(tempStrategy.getIndex())));
            HTML.makeNewLine();
        }
        SaveData tempSave = new CharFile("result", "htm");
        tempSave.write(HTML.endText());
>>>>>>> .r11
        //while(data.downloadData()){}
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Mediator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Mediator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Mediator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Mediator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */

                getRef();

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
